/* 友情链接 */
const router = require("koa-router")();

const DB = require("../../module/db.js");

const tools = require("../../module/tools.js");

router.get("/", async (ctx) => {
  let page = ctx.query.page || 1;
  let pageSize = 3;
  let result = await DB.find("link", {}, {}, pageSize, page, { add_time: -1 });
  let count = await DB.count("link", {}); /*总数量*/
  await ctx.render("admin/link/list", {
    list: result,
    page: page,
    totalPages: Math.ceil(count / pageSize),
  });
});

router.get("/addLink", async (ctx) => {
  await ctx.render("admin/link/add");
});

router.post("/doAddLink", tools.multer().single("pic"), async (ctx) => {
  let title = ctx.req.body.title;

  let pic = ctx.req.file ? ctx.req.file.path.substr(7) : "";

  let url = ctx.req.body.url;

  let status = parseInt(ctx.req.body.status);

  let add_time = tools.getTime();

  await DB.insert("link", {
    title,
    pic,
    url,
    status,
    add_time,
  });
  //跳转
  ctx.redirect(ctx.state.__HOST__ + "/admin/link");
});

//编辑
router.get("/editLink", async (ctx) => {
  let id = ctx.query.id;
  let result = await DB.find("link", { _id: DB.getObjectId(id) });

  await ctx.render("admin/link/edit", {
    list: result[0],
    prevPage: ctx.state.G.prevPage,
  });
});

//执行编辑数据
router.post("/doEditLink", tools.multer().single("pic"), async (ctx) => {
  let id = ctx.req.body.id;

  let title = ctx.req.body.title;

  let pic = ctx.req.file ? ctx.req.file.path.substr(7) : "";

  let url = ctx.req.body.url;

  let status = ctx.req.body.status;

  let add_time = tools.getTime();

  let prevPage = ctx.req.body.prevPage;

  if (pic) {
    var json = {
      title,
      pic,
      url,
      status,
      add_time,
    };
  } else {
    var json = {
      title,
      url,
      status,
      add_time,
    };
  }
  await DB.update("link", { _id: DB.getObjectId(id) }, json);

  if (prevPage) {
    ctx.redirect(prevPage);
  } else {
    //跳转
    ctx.redirect(ctx.state.__HOST__ + "/admin/link");
  }
});

module.exports = router.routes();
